from rest_framework import serializers
from django_redis import get_redis_connection
import re


class ImageCodeCheckSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4, min_length=4)
    image_code_id = serializers.UUIDField()

    def validate(self, attrs):
        image_code_id = attrs.get('image_code_id', '')
        text = attrs.get('text', '')
        redis_conn = get_redis_connection('verify_codes')
        real_text = redis_conn.get("image_%s" % image_code_id, '')
        # 防止暴力测试
        redis_conn.delete("image_%s" % image_code_id)
        if not real_text:
            raise serializers.ValidationError('验证码不存在')
        if real_text.decode().lower() != text.lower():
            raise serializers.ValidationError('验证码输入错误')

        mobile = self.context['view'].kwargs['mobile']
        result = re.match(r'1[3-9]\d{9}', mobile)
        if not result:
            raise serializers.ValidationError('手机号格式错误')
        real_data = redis_conn.get('flag_%s' % mobile)
        if real_data:
            raise serializers.ValidationError('发送短信过于频繁')
        return attrs

